package com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextFile {

	
	public static void main(String[] args) {
		TextFile tf = new TextFile();
		//-----------------------------------------------
		
        String rName = "CnCiku7.txt";
        String wName = "CnCiku71.txt";
        
        tf.rwTextFile(rName, wName, 1);
        
        System.out.println("FileText Finished!");


		
	}

	// text文件，按行读出，存入List<String>
	public static List<String> fxReadTxtFile(String txtFile) 
	{
		// 
		List<String> txtData = new ArrayList<String>();
		if(txtFile==null||txtFile.length()==0) {
			System.out.println("File Name error:" + txtFile);
			return txtData;
		}
		
		// 判断文件是否存在
		File file = new File(txtFile);
		if(!file.exists()) {
			System.out.println("File not exist:" + txtFile);
			return txtData;
		}
		
        FileReader fr = null;
        BufferedReader br = null;
        // 逐行读取文件
        try {
			fr = new FileReader(txtFile);
			br = new BufferedReader(fr);
			String line = null;
			while ((line = br.readLine()) != null) {
				line.stripIndent();
		        if(line.length()==0) {
		        	continue;
		        }
		        /*
		        String[] ws = line.split("\\s+");
		        if( ws.length <2) {
		        	continue;
		        }
		        System.out.println(ws[0]);
		        */
		        //
		        txtData.add(line);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) { 
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        finally{
        	file=null;
        	try {
				if(br != null){
					br.close();
				}
				if(fr != null){
					fr.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        
		return txtData;
	}

	// 分析 读入的数独数据 是否符合格式？
	public static List<String> parseText2Sentence(String txtFile) {
		List<String> txt = fxReadTxtFile(txtFile);
		int cntLines = txt.size();
		if (cntLines < 1) {
			return null;
		}
        for(String s : txt) {
        	System.out.println(s);
        }
		//
		List<String> sents = new ArrayList<String>();
		int lineNo = 0;
		String line = "";
		while(lineNo < cntLines) {
			line = txt.get(lineNo);
			line = line.trim();
			// * | . ^ 等符号在正则表达式中属于一种有特殊含义的字符，如果使用此种字符作为分隔符，必须使用转义符即\\加以转义。
	        // 测试正则表达式
	        Pattern p = Pattern.compile(".*?[，。？！；;!?]");
			Matcher m = p.matcher(line);
			String st;
			while(m.find()) {
				st = m.group(0);
				sents.add(st);
				// 分开的句子
				System.out.println(st);
			}
			lineNo++;
		}
		return sents;
	}

    // 采用流（Stream）的方式来读取文件, 输出文件。
    public void rwTextFile(String rName, String wName, int wLen)   {
		List<String> lines = new ArrayList<String>();
		// 可以读取不同编码的文件：gb2312, utf-8
    	try {
	        if (rName == null || rName.length() == 0) {
	        	System.out.println("File Name Error: " + rName);
	            return;
	        }
	        String path = System.getProperty("user.dir") + "\\resource\\";
	        String iname = path + rName;
        	System.out.println("Path: " + iname);
	        File file = new File(path);
	        if(!file.exists()) { 
	        	System.out.println("File Find Error: " + rName);
	            return;
	        }
	        // 读取文件要先生成 读取流 BufferedReader
	        InputStream is = new FileInputStream(iname);
	        InputStreamReader isr = new InputStreamReader(is);
	        BufferedReader br = new BufferedReader(isr);
	        
	        String line = "";
	        int ncnt = 0;
	        //StringBuilder sb = new StringBuilder();
	        while ((line = br.readLine()) != null) {
	        	line = line.trim();
/*	        	
		        String[] ws = line.split("\\s+");
		        if( ws.length <2) {
		        	continue;
		        }
		        if( ws[1].length() != wLen) {
		        	continue;
		        }
*/		        
		        ncnt++;
	            lines.add("" + ncnt + "\t" + line + "\t" + "1");
	            System.out.println("" + ncnt + "\t" + line + "\t" + "1");
	        }
	        br.close();
	        isr.close();
	        is.close();
	
	        // 将读入的内容写入文件
	        String fileOut = path + wName;
	        // 输出文件要先生成流 Bufferedwriter
	        OutputStream os = new FileOutputStream(fileOut);
	        OutputStreamWriter osr = new OutputStreamWriter(os);
	        BufferedWriter bw = new BufferedWriter(osr);
	        // 遍历 HashMap, 输出 <key, value>
	        if(lines!=null && (!lines.isEmpty())) {
				for (String ln : lines) {
					bw.write(ln+"\r\n");
					System.out.println("Out: " + ln);
				}
		    }
			bw.close();
			osr.close();
			os.close();
    	}
    	catch(Exception e) {
    		e.printStackTrace();
    	}

    }

}
